package com.dennytech.tac.statistics;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import com.dennytech.tac.base.CFApplication;
import com.dennytech.tac.base.Environment;
import com.dennytech.tac.net.NetworkInfoHelper;
import com.dennytech.tac.utils.Daemon;
import com.dennytech.tac.utils.Log;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;

class GoogleAnalyticsHandler extends Handler {
	public static final int PAGE_VIEW = 5;
	public static final int EVENT = 6;
	public static final int SESSION_START = 1;
	public static final int SESSION_END = 2;

	private static boolean started; // the started status is global
	private final GoogleAnalyticsTracker tracker;
	private NetworkInfoHelper networkInfo;

	public GoogleAnalyticsHandler(Context context) {
		super(Daemon.looper());
		tracker = GoogleAnalyticsTracker.getInstance();
		networkInfo = new NetworkInfoHelper(context);
	}

	public void prepare() {
		if (!started) {
			try {
				tracker.startNewSession("UA-35620712-1", 120, CFApplication.instance());
				tracker.setCustomVar(1, "version", Environment.version(), 1);
				tracker.setCustomVar(2, "source", Environment.source(), 1);
				tracker.setCustomVar(3, "network",
						networkInfo.getNetworkInfo(), 2);
				tracker.setCustomVar(4, "os_version", Build.VERSION.RELEASE, 1);
				started = true;
			} catch (Exception e) {
				Log.e("statistics", "unable to start google analytics tracket",
						e);
			}
		}
	}

	public void stop() {
		if (started) {
			tracker.stopSession();
			started = false;
		}
	}

	@Override
	public void handleMessage(Message msg) {
		if (msg.what == PAGE_VIEW) {
			prepare();
			tracker.trackPageView((String) msg.obj);
		} else if (msg.what == EVENT) {
			prepare();
			try {
				Object[] arr = (Object[]) msg.obj;
				String category = (String) arr[0];
				String action = (String) arr[1];
				String label = (String) arr[2];
				int value = (Integer) arr[3];
				tracker.trackEvent(category, action, label, value);
			} catch (Exception e) {
			}
		} else if (msg.what == SESSION_START) {
			prepare();
		} else if (msg.what == SESSION_END) {
			stop();
		}
	}
}
